#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

#define N 64

int main(int argc, char const *argv[])
{
    int broadfd;

    //创建一个socket文件描述符
    broadfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(broadfd < 0)
    {
        perror("sock err");
        return -1;
    }

    //绑定套接字(ip+port)
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(7788);  //端口号
    addr.sin_addr.s_addr = INADDR_ANY;

    int addrlen = sizeof(addr);
    
    if(bind(broadfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("bind err");
        return -1;
    }

    ssize_t len;
    char buf[N] = {0};
    struct sockaddr_in cliaddr;
    
    //接收"coffee"搜索包
    bzero(buf, N);
    len = recvfrom(broadfd, buf, N, 0, (struct sockaddr *)&cliaddr, &addrlen);

    //判断是否是本公司产品：收到的数据是否"coffee"
    if(strcmp(buf, "jinan") != 0)
    {
        printf("not my jinan\n");
        return -1;
    }

    //回复yes，告诉软件，我收到了搜索协议，并且回复地址
    sendto(broadfd, "yes", 4, 0, (struct sockaddr *)&cliaddr, addrlen);

    //变身为TCP服务器，准备接收软件的升级文件
    int tcpfd = socket(AF_INET, SOCK_STREAM, 0);
    if(tcpfd < 0)
    {
        perror("sock err");
        return -1;
    }

    if(bind(tcpfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("bind err");
        return -1;
    }

    //监听套接字
    if(listen(tcpfd, 5) < 0)
    {
        perror("listen err");
        return -1;
    }

    //接收客户端的连接
    printf("wait client connect\n");
    int clifd;
    
    //接收对端的地址
    clifd = accept(tcpfd, NULL, NULL);
    if(clifd < 0)
    {
        perror("accept err");
        return -1;
    }

    printf("new cononect coming\n");    

     return 0;
 }